package com.weme.matching.view

import android.content.Context
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.TextView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.osom.proto.message.Brocast
import com.weme.common.util.getCountryBean
import com.weme.common.util.loadImage
import com.weme.matching.databinding.ViewMatchingSuccessBinding

class ViewMatchingSuccess @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyle: Int = 0
) : FrameLayout(context, attributeSet, defStyle), LifecycleObserver {

    private val viewBinding =
        ViewMatchingSuccessBinding.inflate(LayoutInflater.from(context), this, true)

    private val player: ExoPlayer by lazy {
        ExoPlayer.Builder(context).build()
    }


    fun getTvContent():TextView{
        return viewBinding.tvContent
    }
    init {
        // 注册生命周期监听器
        if (context is LifecycleOwner) {
            context.lifecycle.addObserver(this)
        }
    }

    fun initView(base: Brocast.MatchMessage) {
//        val contentType = base.matchedUser.cover.getContentType()
//        if (contentType != null) {
//            if (contentType.startsWith("image")) {
//                viewBinding.imView.loadImage(base.matchedUser.cover)
//            } else if (contentType.startsWith("video")) {
//                staPlay(base.matchedUser.cover)
//            }
//        }
        viewBinding.imView.loadImage(base.matchedUser.cover)
        viewBinding.head.loadImage(base.matchedUser.avatar)
        viewBinding.tvName.text = String.format(base.matchedUser.nickname+","+base.matchedUser.age)
        val country = getCountryBean(base.matchedUser.countryCode)
        country?.let {
            viewBinding.imCountry.loadImage(it.countryFlag)
            viewBinding.tvLanguage.text= it.countryName
        }

        // 其他初始化逻辑...
    }

    private fun staPlay(url: String) {
        viewBinding.playerView.player = player
        player.repeatMode = Player.REPEAT_MODE_ONE
        player.volume = 0f

        val videoUri: Uri = Uri.parse(url)
        val mediaItem = MediaItem.fromUri(videoUri)
        player.setMediaItem(mediaItem)
        player.prepare()
        player.playWhenReady = true

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        player.playWhenReady = false
        player.release()
    }
}
